<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="职位名称:">
        <el-input placeholder="请你输入搜索职位" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
          >搜索</el-button
        >
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser"
      >添加职位</el-button
    >

    <!-- table展示用户信息 -->
    <el-table style="margin: 10px 0px" border :data="userArr">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建世间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="any"
            @click="setRole(row)"
            >分配权限</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除${row.roleName}?`"
            width="260px"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ userParams.id ? "更新职位" : "添加职位" }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="职位姓名" prop="roleName">
          <el-input
            placeholder="请您输入职位姓名"
            v-model="userParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <el-tree
        ref="tree"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="defaultProps"
        :default-checked-keys="selectArr"
      />
    </template>
    <!-- :default-checked-keys="[5]" 默认选中 -->
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import useLayOutSettingStore from "@/store/modules/setting";
import { ref, onMounted, reactive, nextTick, watch } from "vue";
import {
  GetListResponseData,
  GetListResponseRecords,
  MenuResponseData,
  MenuList,
} from "@/api/acl/role/type";
import {
  reqGetRoleList,
  reqAddOrUpdateUser,
  reqRemoveUser,
  reqAllRole,
  reqSetUserRole,
} from "@/api/acl/role/index";
import { ElMessage } from "element-plus";
const defaultProps = {
  children: "children",
  label: "name",
};
const tree = ref<any>();
//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(10);
//用户总个数
let total = ref<number>(0);
//存储全部用户的数组
let userArr = ref<GetListResponseRecords>([]);
//定义响应式数据控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
//控制分配角色抽屉显示与隐藏
let drawer1 = ref<boolean>(false);

// 树形控件值
let menuArr = ref<any>([]);
// 默认选择的
let selectArr = ref<any>([]);
//收集用户信息的响应式数据
let userParams = reactive<any>({
  roleName: "",
});
//获取form组件实例
let formRef = ref<any>();
//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>("");
//获取模板setting仓库
let settingStore = useLayOutSettingStore();
//组件挂载完毕
onMounted(() => {
  getHasUser();
});
//获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  const result: GetListResponseData = await reqGetRoleList(
    pager,
    pageSize.value,
    keyword.value
  );
  if (result.code == 200) {
    total.value = result.data.total;
    userArr.value = result.data.records;
  }
};
//分页器下拉菜单的自定义事件的回调
const handler = () => {
  getHasUser();
};
//添加用户按钮的回调
const addUser = () => {
  drawer.value = true;
  Object.assign(userParams, {
    id: 0,
    roleName: "",
  });
  nextTick(() => {
    formRef.value.clearValidate("roleName");
  });
};
//更新已有的用户按钮的回调
//row:即为已有用户的账号信息
const updateUser = (row: any) => {
  //抽屉显示出来
  drawer.value = true;
  //存储收集已有的账号信息
  Object.assign(userParams, row);
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate("roleName");
  });
};
//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //保存按钮:添加新的用户|更新已有的用户账号信息
  let result: any = await reqAddOrUpdateUser(userParams);
  //添加或者更新成功
  if (result.code == 200) {
    //关闭抽屉
    drawer.value = false;
    //提示消息
    ElMessage({
      type: "success",
      message: userParams.id ? "更新成功" : "添加成功",
    });
    //获取最新的全部账号的信息
    // getHasUser(userParams.id ? pageNo.value : 1);
    //浏览器自动刷新一次
    reset();
  } else {
    //关闭抽屉
    drawer.value = false;
    //提示消息
    ElMessage({
      type: "error",
      message: userParams.id ? "更新失败" : "添加失败",
    });
  }
};
//取消按钮的回调
const cancel = () => {
  //关闭抽屉
  drawer.value = false;
};
//校验角色字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  //角色字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("角色字至少五位"));
  }
};
//校验角色字回调函数
const validatorname = (rule: any, value: any, callBack: any) => {
  //角色字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack();
  } else {
    callBack(new Error("用户昵称至少五位"));
  }
};
const validatorPassword = (rule: any, value: any, callBack: any) => {
  //角色字|昵称,长度至少五位
  if (value.trim().length >= 6) {
    callBack();
  } else {
    callBack(new Error("用户密码至少六位"));
  }
};
//表单校验的规则对象
const rules = {
  //角色字
  roleName: [{ required: true, trigger: "blur", validator: validatorUsername }],
};
//分配角色按钮的回调
const setRole = async (row: GetListResponseRecords) => {
  //存储已有的用户信息
  Object.assign(userParams, row);
  //获取全部的职位的数据与当前用户已有的职位的数据
  let result: MenuResponseData = await reqAllRole(userParams.id as number);
  if (result.code == 200) {
    console.log(result, "result");

    //   //抽屉显示出来
    menuArr.value = result.data;
    drawer1.value = true;
    selectArr.value = filterSelectArr(menuArr.value, []); //递归找出已分配的权限
  }
};
const filterSelectArr = (allData: MenuList, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr);
    }
  });

  return initArr;
};
//收集顶部复选框全选数据
const checkAll = ref<boolean>(false);
//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true);

//确定按钮的回调(分配菜单)
const confirmClick = async () => {
  const roleId = userParams.id as number;
  const getHalfCheckedKeys = tree.value.getHalfCheckedKeys(); //班选
  const getCheckedKeys = tree.value.getCheckedKeys(); //全选
  const permissionId = getHalfCheckedKeys.concat(getCheckedKeys);
  console.log(roleId, getHalfCheckedKeys, getCheckedKeys, permissionId);
  const result: any = await reqSetUserRole(roleId, permissionId);
  if (result.code == 200) {
    //抽屉关闭
    drawer.value = false;
    //提示信息
    ElMessage({ type: "success", message: "分配权限成功" });
    //页面刷新
    reset();
  }
};

//删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId);
  if (result.code == 200) {
    ElMessage({ type: "success", message: "删除成功" });
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};

//搜索按钮的回调
const search = () => {
  //根据关键字获取相应的用户数据
  getHasUser();
  //清空关键字
  keyword.value = "";
};
//重置按钮
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};
watch(drawer1, (newValue: boolean) => {
  if (!newValue) return (selectArr.value = []);
});
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
